package JUC;

/**
 * @author 豆包LU
 * @date 2023/5/8 17:57
 */
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import java.util.concurrent.*;

public class ProducerConsumerExampleBaoZi {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个容量为10的阻塞队列
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        // 创建2个工人，同时启动
        for (int i = 0; i < 2; i++) {
            executorService.execute(new Producer(queue));
        }

        // 创建3个顾客，同时启动
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Consumer(queue));
        }

        // 主线程休眠5秒钟
        Thread.sleep(5000);

        // 关闭线程池，停止生产和消费
        executorService.shutdownNow();
    }
}

// 生产者
class Producer implements Runnable {
    private final ArrayBlockingQueue<String> queue;

    public Producer(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                // 随机生成一个包子
                String baozi = "包子" + ThreadLocalRandom.current().nextInt(1000);
                // 将包子放入阻塞队列
                queue.put(baozi);
                System.out.println(Thread.currentThread().getName() + " 生产了一个" + baozi + "，现在队列中有" + queue.size() + "个包子");
                // 等待一段时间再生产
                Thread.sleep(5000);
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " 被中断，停止生产");
        }
    }
}

// 消费者
class Consumer implements Runnable {
    private final ArrayBlockingQueue<String> queue;

    public Consumer(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                // 从阻塞队列中取出一个包子
                String baozi = queue.poll(2L,TimeUnit.SECONDS);
                if (baozi==null||"".equals(baozi)){
                    System.out.println(Thread.currentThread().getName() + " 退出消费");
                }else {
                    System.out.println(Thread.currentThread().getName() + " 买到了" + baozi + "，现在队列中有" + queue.size() + "个包子");
                }
                // 等待一段时间再购买
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " 被中断，停止购买");
        }
    }
}

